package com.zl.learning.io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipeTest {
    static class PipeSender implements Runnable {

        private PipedOutputStream pos = null;

        public PipeSender() {
            this.pos = new PipedOutputStream();
        }

        @Override
        public void run() {
            String str = "Hello!Amgio.";
            try {
                this.pos.write(str.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    this.pos.close();
                } catch (IOException ignored) {

                }
            }
        }

        public PipedOutputStream getPos() {
            return pos;
        }
    }

    static class PipeReceiver implements Runnable {
        private PipedInputStream pis = null;

        public PipeReceiver() {
            this.pis = new PipedInputStream();
        }

        @Override
        public void run() {
            byte[] b = new byte[1024];
            int len = 0;
            try {
                len = this.pis.read(b);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    this.pis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Recive content :" + new String(b, 0, len));
        }

        public PipedInputStream getPis() {
            return pis;
        }
    }

    public static void main(String[] args) {
        PipeSender sender = new PipeSender();
        PipeReceiver receiver = new PipeReceiver();
        try {
            sender.getPos().connect(receiver.getPis());
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Thread(sender).start();
        new Thread(receiver).start();
    }
}
